﻿Ext.define('Wiztop.custom.ImageViewer', {
    extend: 'Ext.Container',
    config: {
        doubleTapScale: 1,
        maxScale: 4,
        loadingMask: true,
        previewSrc: false,
        resizeOnLoad: true,
        imageSrc: 'resources/images/temp.png',
        drawSrc: '',
        initOnActivate: false,
        isDraw: false,
        titleHeight: 50,
        cls: 'imageBox',
        scrollable: 'both',
        drawMode: "Pencil",
        brushColor: 'green',
        brushSize: 6,
        mainSync: false, //当前用户为主讲人时，使用的同步状态变量
        subSync: false, //当前用户为被同步人时，使用的同步状态变量
        html: '<figure><canvas style="position:absolute;"></canvas><canvas style="position:absolute;"></canvas></figure>',
        listeners: {
            resize: function (component, eOpts) {
                this.rotate();
            }
        }
    },
    xtype: 'imageviewer',
    initialize: function () {
        this.lines = [, , ];
        this.isInk = 1;
        this.currentIndex = 0;
        this.pixels = new Array();
        this.startDraw = false;
        this.getScrollable().getScroller().on('scrollend', this.onScrollerEnd, this);
        if (this.initOnActivate)
            this.addListener('activate', this.initViewer, this, { delay: 10, single: true });
        else
            this.addListener('painted', this.initViewer, this, { delay: 10, single: true });
    },
    initViewer: function () {
        //disable scroller
        var scroller = this.getScrollable().getScroller();
        scroller.setDisabled(true);
        // mask image viewer
        if (this.getLoadingMask())
            this.setMasked({
                xtype: 'myloadmask'
            });
        // retrieve DOM els        
        this.figEl = this.element.down('figure');

        this.imgEl = this.figEl.down('canvas');
        this.drawEl = Ext.get(Ext.DomQuery.select("canvas", this.element.dom)[1]); // 

        this.ctx = this.imgEl.dom.getContext('2d');
        this.ctxDraw = this.drawEl.dom.getContext('2d');
        //
        //apply required styles
        this.figEl.setStyle({
            overflow: 'hidden',
            display: 'block',
            margin: 0
        });
        this.imgEl.setStyle({
            '-webkit-user-drag': 'none',
            '-webkit-transform-origin': '0 0',
            'visibility': 'hidden'
        });

        this.drawEl.setStyle({
            '-webkit-user-drag': 'none',
            '-webkit-transform-origin': '0 0',
            'visibility': 'hidden'
        });
        // show preview
        if (this.getPreviewSrc()) {
            this.element.setStyle({
                backgroundImage: 'url(' + this.getPreviewSrc() + ')',
                backgroundPosition: 'center center',
                backgroundRepeat: 'no-repeat',
                webkitBackgroundSize: 'contain'
            });
        }
        // attach event listeners
        //        this.imgEl.addListener({
        //            scope: this,
        //            doubletap: this.onDoubleTap,
        //            pinchstart: this.onImagePinchStart,
        //            pinch: this.onImagePinch,
        //            pinchend: this.onImagePinchEnd
        //        });

        this.drawEl.addListener({
            scope: this,
            doubletap: this.onDoubleTap,
            pinchstart: this.onImagePinchStart,
            pinch: this.onImagePinch,
            pinchend: this.onImagePinchEnd,
            touchstart: this.onPreDraw,
            touchmove: this.onDraw//,touchend: this.endDraw
        });
        // load image
        if (this.getImageSrc()) {
            this.loadImage(this.getImageSrc());
        }
        else
            this.onImageLoad();
    },
    refreshImage: function () {
        this.image = null;
        this.drawImage = null;
        this.initViewer();
    },
    resetImageSrc: function (imgSrc, drawSrc) {
        this.resetZoom();
        this.image = null;
        this.drawImage = null;
        //console.log("pinchzoomimage:applySrc",value)
        this.setDrawSrc(drawSrc);
        if (imgSrc != null && imgSrc != "") {
            this.setImageSrc(imgSrc);
            this.loadImage(imgSrc);
        }
        else {
            this.resetDrawSrc(drawSrc);
        }
    },
    loadImage: function (src) {
        if (this.imgEl) {
            var img = this.getImage();
            img.src = src;
        }
        else
            this.setImageSrc(src);
    },
    /**
    * [getImage create and get image buffer]
    */
    getImage: function () {
        if (this.image == null) {
            this.image = new Image();
            var me = this;
            this.image.onload = (function (m) {
                return function () {
                    m.drawImageBg();
                    //
                    m.resetDrawSrc(me.getDrawSrc());
                    //m.onImageLoad();
                }
            })(this);
        }
        return this.image;
    },
    drawImageBg: function () {
        if (this.image != null && this.image.complete == true && this.ctx != null) {
            //
            this.ctx.clearRect(0, 0, this.imgEl.dom.width, this.imgEl.dom.height);
            this.ctxDraw.clearRect(0, 0, this.drawEl.dom.width, this.drawEl.dom.height);
            //
            this.drawEl.dom.width = this.image.width;
            this.drawEl.dom.height = this.image.height;
            this.imgEl.dom.width = this.srcWidth = this.image.width;
            this.imgEl.dom.height = this.srcHeight = this.image.height;

            this.destWidth = this.imgEl.dom.width;
            this.destHeight = this.imgEl.dom.height;

            this.ratioWidth = this.srcWidth / this.destWidth;
            this.ratioHeight = this.srcHeight / this.destHeight;

            if (this.ratioWidth > this.ratioHeight) {
                this.destHeight = this.srcHeight / this.ratioWidth;
            } else {
                this.destWidth = this.srcWidth / this.ratioHeight;
            }

            this.srcX = 0;
            this.srcY = 0;

            this.destX = (this.imgEl.dom.width - this.destWidth) / 2;
            this.destY = (this.imgEl.dom.height - this.destHeight) / 2;

            //生成背景
            this.ctx.drawImage(this.image, this.srcX, this.srcY, this.srcWidth, this.srcHeight, this.destX, this.destY, this.destWidth, this.destHeight);
        }
    },
    //
    resetDrawSrc: function (value) {
        if (value != null && value != "") {
            this.setDrawSrc(value);
            this.loadDrawImage(value);
        }
        else {
            this.onImageLoad();
        }
    },
    loadDrawImage: function (src) {
        if (this.drawEl) {
            var img = this.getDrawImage();
            img.src = src + "?temp=" + Date.parse(new Date());
        }
        else
            this.setDrawSrc(src);
    },
    getDrawImage: function () {
        if (this.drawImage == null) {
            this.drawImage = new Image();
            var me = this;
            this.drawImage.onload = (function (m) {
                return function () {
                    m.drawDrawBg();
                    m.onImageLoad();
                }
            })(this);
        }
        return this.drawImage;
    },
    drawDrawBg: function () {
        if (this.drawImage != null && this.drawImage.complete == true && this.ctxDraw != null) {
            //           
            this.ctxDraw.clearRect(0, 0, this.drawEl.dom.width, this.drawEl.dom.height);
            //
            this.drawEl.dom.width = this.srcWidth = this.imgEl.dom.width;
            this.drawEl.dom.height = this.srcHeight = this.imgEl.dom.height;


            this.destWidth = this.drawEl.dom.width;
            this.destHeight = this.drawEl.dom.height;

            this.ratioWidth = this.srcWidth / this.destWidth;
            this.ratioHeight = this.srcHeight / this.destHeight;

            if (this.ratioWidth > this.ratioHeight) {
                this.destHeight = this.srcHeight / this.ratioWidth;
            } else {
                this.destWidth = this.srcWidth / this.ratioHeight;
            }

            this.srcX = 0;
            this.srcY = 0;

            this.destX = (this.drawEl.dom.width - this.destWidth) / 2;
            this.destY = (this.drawEl.dom.height - this.destHeight) / 2;

            //生成背景
            this.ctxDraw.drawImage(this.drawImage, this.srcX, this.srcY, this.srcWidth, this.srcHeight, this.destX, this.destY, this.destWidth, this.destHeight);
        }
    },
    //
    onImageLoad: function () {


        // get viewport size
        this.viewportWidth = this.viewportWidth || this.getWidth() || this.parent.element.getWidth();
        this.viewportHeight = this.viewportHeight || this.getHeight() || this.parent.element.getHeight();
        //alert(this.viewportWidth + "  " + this.viewportHeight);
        // grab image size
        this.imgWidth = this.imgEl.dom.width;
        this.imgHeight = this.imgEl.dom.height;
        // calculate and apply initial scale to fit image to screen
        if (this.getResizeOnLoad()) {
            this.scale = this.baseScale = Math.min(this.viewportWidth / this.imgWidth, this.viewportHeight / this.imgHeight);
            this.setMaxScale(this.scale * 4);
        }
        else {
            this.scale = this.baseScale = 1;
        }

        // set initial translation to center
        this.translateX = this.translateBaseX = (this.viewportWidth - this.baseScale * this.imgWidth) / 2;
        this.translateY = this.translateBaseY = (this.viewportHeight - this.baseScale * this.imgHeight) / 2;
        // apply initial scale and translation
        this.applyTransform();
        // initialize scroller configuration
        this.adjustScroller();
        // show image and remove mask
        this.imgEl.setStyle({ visibility: 'visible' });
        this.drawEl.setStyle({ visibility: 'visible' });
        // remove preview
        if (this.getPreviewSrc()) {
            this.element.setStyle({
                backgroundImage: 'none'
            });
        }

        if (this.getLoadingMask())
            this.setMasked(false);
        //this.fireEvent('imageLoaded', this);
    },
    /*界面缩放*/
    onImagePinchStart: function (ev) {
        this.imagePinchStart(ev.touches[0].pageX, ev.touches[0].pageY, ev.touches[1].pageX, ev.touches[1].pageY);
        if (this.getMainSync()) {
            //如果是同步，将事件发给对方       
            //alert(ev.touches[0].pageX + "  " + ev.touches[0].pageY);
            //alert(ev.touches[0].pageX + "  " + ev.touches[0].pageY + "  " + ev.touches[1].pageX + "  " + ev.touches[1].pageY);
            sendPinchStartMessage(ev.touches[0].pageX, ev.touches[0].pageY, ev.touches[1].pageX, ev.touches[1].pageY);
        }
    },
    imagePinchStart: function (x1, y1, x2, y2) {
        if (this.getIsDraw()) return;
        var scroller = this.getScrollable().getScroller();
        // disable scrolling during pinch
        scroller.stopAnimation();
        scroller.setDisabled(true);
        // store beginning scale
        this.startScale = this.scale;
        //calculate touch midpoint relative to image viewport
        this.originViewportX = (x1 + x2) / 2 - this.element.getX();
        this.originViewportY = (y1 + y2) / 2 - this.element.getY();
        // translate viewport origin to position on scaled image
        this.originScaledImgX = this.originViewportX + scroller.position.x - this.translateX;
        this.originScaledImgY = this.originViewportY + scroller.position.y - this.translateY;
        // unscale to find origin on full size image
        this.originFullImgX = this.originScaledImgX / this.scale;
        this.originFullImgY = this.originScaledImgY / this.scale;
        // calculate translation needed to counteract new origin and keep image in same position on screen
        this.translateX += (-1 * ((this.imgWidth * (1 - this.scale)) * (this.originFullImgX / this.imgWidth)));
        this.translateY += (-1 * ((this.imgHeight * (1 - this.scale)) * (this.originFullImgY / this.imgHeight)))
        // apply new origin
        this.setOrigin(this.originFullImgX, this.originFullImgY);
        // apply translate and scale CSS
        this.applyTransform();
    },
    onImagePinch: function (ev) {
        this.imagePinch(ev.scale);
        //
        if (this.getMainSync()) {
            //如果是同步，将事件发给对方
            sendPinchMessage(ev.scale);
        }
    },
    imagePinch: function (scale) {
        if (this.getIsDraw()) return;
        // prevent scaling to smaller than screen size
        this.scale = Ext.Number.constrain(scale * this.startScale, this.baseScale - 2, this.getMaxScale());
        this.applyTransform();
    },
    onImagePinchEnd: function (ev) {
        this.imagePinchEnd();
        //
        if (this.getMainSync()) {
            //如果是同步，将事件发给对方
            sendPinchEndMessage()
        }
    },
    imagePinchEnd: function () {
        if (this.getIsDraw()) return;
        // set new translation
        if (this.scale == this.baseScale) {
            // move to center
            this.setTranslation(this.translateBaseX, this.translateBaseY);
        }
        else {
            //Resize to init size like ios
            if (this.scale < this.baseScale && this.getResizeOnLoad()) {
                this.resetZoom();
                return;
            }
            // calculate rescaled origin
            this.originReScaledImgX = this.originScaledImgX * (this.scale / this.startScale);
            this.originReScaledImgY = this.originScaledImgY * (this.scale / this.startScale);
            // maintain zoom position
            this.setTranslation(this.originViewportX - this.originReScaledImgX, this.originViewportY - this.originReScaledImgY);
        }
        // reset origin and update transform with new translation
        this.setOrigin(0, 0);
        this.applyTransform();
        // adjust scroll container
        this.adjustScroller();
    },
    onDoubleTap: function (ev, t) {
        var originViewportX = ev ? (ev.pageX - this.element.getX()) : 0,
        originViewportY = ev ? (ev.pageY - this.element.getY()) : 0;
        this.doubleTap(originViewportX, originViewportY);
        //
        if (this.getMainSync()) {
            //如果是同步，将事件发给对方
            sendDoubleTapMessage(originViewportX, originViewportY);
        }
    },
    doubleTap: function (originViewportX, originViewportY) {
        //if (this.getIsDraw()) return;
        var that = this;
        var scroller = this.getScrollable().getScroller();
        if (!this.getDoubleTapScale())
            return false;
        // set scale and translation
        if (this.scale > this.baseScale) {
            // zoom out to base view
            this.scale = this.baseScale;
            this.setTranslation(this.translateBaseX, this.translateBaseY);
            // reset origin and update transform with new translation
            this.applyTransform();
            // adjust scroll container
            this.adjustScroller();
            // force repaint to solve occasional iOS rendering delay
            Ext.repaint();
        }
        else {
            // zoom in toward tap position
            var oldScale = this.scale, newScale = this.baseScale * 4,
            //originViewportX = ev ? (ev.pageX - this.element.getX()) : 0,
            //originViewportY = ev ? (ev.pageY - this.element.getY()) : 0,
            originScaledImgX = originViewportX + scroller.position.x - this.translateX,
            originScaledImgY = originViewportY + scroller.position.y - this.translateY,
            originReScaledImgX = originScaledImgX * (newScale / oldScale),
            originReScaledImgY = originScaledImgY * (newScale / oldScale);
            this.scale = newScale;
            //smoothes the transition
            setTimeout(function () {
                that.setTranslation(originViewportX - originReScaledImgX, originViewportY - originReScaledImgY);
                // reset origin and update transform with new translation
                that.applyTransform();
                // adjust scroll container
                that.adjustScroller();
                // force repaint to solve occasional iOS rendering delay
                Ext.repaint();
            }, 50)
        }
    },
    setOrigin: function (x, y) {
        this.imgEl.dom.style.webkitTransformOrigin = x + 'px ' + y + 'px';
        //
        this.drawEl.dom.style.webkitTransformOrigin = x + 'px ' + y + 'px';
    },
    setTranslation: function (translateX, translateY) {
        this.translateX = translateX;
        this.translateY = translateY;
        // transfer negative translations to scroll offset
        this.scrollX = this.scrollY = 0;
        if (this.translateX < 0) {
            this.scrollX = this.translateX;
            this.translateX = 0;
        }
        if (this.translateY < 0) {
            this.scrollY = this.translateY;
            this.translateY = 0;
        }
    },
    resetZoom: function () {
        if (this.imgEl && this.drawEl && this.scale != this.baseScale) {
            //Resize to init size like ios
            this.scale = this.baseScale;
            this.setTranslation(this.translateBaseX, this.translateBaseY);
            // reset origin and update transform with new translation
            this.setOrigin(0, 0);
            this.applyTransform();
            // adjust scroll container
            this.adjustScroller();
        }
    },
    rotate: function () {
        var tempDraw = this.getIsDraw();
        this.setIsDraw(false);
        // get viewport size
        this.viewportWidth = this.parent.element.getWidth() || this.viewportWidth || this.getWidth();
        this.viewportHeight = this.parent.element.getHeight() || this.viewportHeight || this.getHeight();
        // grab image size
        this.imgWidth = this.imgEl.dom.width
        this.imgHeight = this.imgEl.dom.height;
        // calculate and apply initial scale to fit image to screen
        if (this.getResizeOnLoad()) {
            this.scale = this.baseScale = Math.min(this.viewportWidth / this.imgWidth, this.viewportHeight / this.imgHeight);
            this.setMaxScale(this.scale * 4);
        } else {
            this.scale = this.baseScale = 1;
        }
        // set initial translation to center
        this.translateX = this.translateBaseX = (this.viewportWidth - this.baseScale * this.imgWidth) / 2;

        this.translateY = this.translateBaseY = (this.viewportHeight - this.baseScale * this.imgHeight) / 2;
        // apply initial scale and translation
        this.applyTransform();
        // initialize scroller configuration
        this.adjustScroller();
        //
        this.setIsDraw(tempDraw);
    },
    applyTransform: function () {
        var fixedX = Ext.Number.toFixed(this.translateX, 5), fixedY = Ext.Number.toFixed(this.translateY, 5), fixedScale = Ext.Number.toFixed(this.scale, 8);
        if (Ext.os.is.Android) {
            this.imgEl.dom.style.webkitTransform =
            //'translate('+fixedX+'px, '+fixedY+'px)'
            //+' scale('+fixedScale+','+fixedScale+')';
            'matrix(' + fixedScale + ',0,0,' + fixedScale + ',' + fixedX + ',' + fixedY + ')'
        }
        else {
            this.imgEl.dom.style.webkitTransform = 'translate3d(' + fixedX + 'px, ' + fixedY + 'px, 0)' + ' scale3d(' + fixedScale + ',' + fixedScale + ',1)';
            //
            this.drawEl.dom.style.webkitTransform = 'translate3d(' + fixedX + 'px, ' + fixedY + 'px, 0)' + ' scale3d(' + fixedScale + ',' + fixedScale + ',1)';
            //
            this.realX = fixedX;
            this.realY = fixedY;
            this.realScale = fixedScale;

            //alert(fixedX + "  " + fixedY);
        }
    },
    adjustScroller: function () {
        var scroller = this.getScrollable().getScroller();
        // disable scrolling if zoomed out completely, else enable it
        if (this.scale == this.baseScale)
            scroller.setDisabled(true);
        else
            scroller.setDisabled(false);
        // size container to final image size
        var boundWidth = Math.max(this.imgWidth * this.scale, this.viewportWidth);
        var boundHeight = Math.max(this.imgHeight * this.scale, this.viewportHeight);
        this.figEl.setStyle({
            width: boundWidth + 'px', height: boundHeight + 'px'
        });
        // update scroller to new content size
        scroller.refresh();
        // apply scroll
        var x = 0;
        if (this.scrollX) {
            x = this.scrollX
        }
        var y = 0;
        if (this.scrollY) {
            y = this.scrollY
        }
        scroller.scrollTo(x * -1, y * -1)
    },
    /*界面绘制*/
    onPreDraw: function (event) {
        if (!this.getIsDraw()) return;
        var touches = new Array();
        $.each(event.touches, function (i, touch) {
            touches.push({ "id": touch.identifier, "x": this.pageX, "y": this.pageY });
        });
        this.preDraw(touches);
        event.preventDefault();
        //
        if (this.getMainSync()) {
            //如果是同步，将事件发给对方
            sendPreDrawMessage(touches);
        }
    },
    preDraw: function (touches) {
        var me = this;
        if (me.getDrawMode() == 'Eraser') {
            me.ctxDraw.save();
            me.ctxDraw.globalCompositeOperation = 'destination-out';
        }
        var scroller = me.getScrollable().getScroller();
        $.each(touches, function (i, touch) {
            var id = touch.id;
            /************************************************************************************************/
            me.lines[id] = { x: (touch.x - me.translateX + scroller.position.x) / me.scale,
                y: (touch.y - me.translateY + scroller.position.y - me.getTitleHeight()) / me.scale,
                x1: touch.x,
                y1: touch.y
            };

            me.currentX = me.lines[id].x;
            me.currentY = me.lines[id].y;
        });

        if (me.getDrawMode() == 'Input') {
            me.generateTextInput();
        }


    },
    onDraw: function (event) {
        if (!this.getIsDraw()) return;
        if (this.getDrawMode() == 'Input') return;
        var touches = new Array();
        $.each(event.touches, function (i, touch) {
            touches.push({ "id": touch.identifier, "x": this.pageX, "y": this.pageY });
        });
        this.draw(touches);
        event.preventDefault();
        //
        if (this.getMainSync()) {
            //如果是同步，将事件发给对方
            sendDrawMessage(touches);
        }
    },
    draw: function (touches) {
        var me = this;
        var scroller = me.getScrollable().getScroller();
        $.each(touches, function (i, touch) {
            var id = touch.id;
            /************************************************************************************************/
            var moveX = (touch.x - me.translateX + scroller.position.x) / me.scale - me.lines[id].x,
                    moveY = (touch.y - me.translateY + scroller.position.y - me.getTitleHeight()) / me.scale - me.lines[id].y;

            var ret = me.move(id, moveX, moveY);

            me.lines[id].x = ret.x;
            me.lines[id].y = ret.y;
        });

    },
    endDraw: function (event) {
        var me = this;
        if (!me.getIsDraw()) return;
        if (me.getDrawMode() == 'Input') return;

        if (me.getMainSync()) {
            me.startDraw = false;
            if (me.coOordinates.length > 2500) {
                me.splitPoints = me.coOordinates.split('#');
                me.newCoordinates = "" + isInk;
                for (i = 1; i < me.splitPoints.length; i++) {
                    me.newCoordinates += "#" + me.splitPoints[i];
                    if (me.newCoordinates.length > 250) {
                        me.newCoordinates = me.newCoordinates;
                        me.pixels.push(me.newCoordinates.toString());
                        me.newCoordinates = "" + me.isInk;
                        i -= 2;
                    }
                }
                if (i >= me.splitPoints.length) {
                    me.newCoordinates = me.newCoordinates;
                    me.pixels.push(me.newCoordinates.toString());
                    me.newCoordinates = "" + me.isInk;
                }
                //$(me.drawEl.dom).trigger("drawmultiple", pixels);
                me.drawMultiplePixel(me.pixels);
            }
            else {
                me.coOordinates = me.coOordinates;
                me.drawPixel(me.coOordinates);
                me.coOordinates = "" + me.isInk;
            }
        }
    },
    move: function (i, changeX, changeY) {
        var me = this;
        //if (!me.getIsDraw()) return;
        me.ctxDraw.lineWidth = me.getBrushSize(); // options.size || Math.ceil(Math.random() * 35);
        me.ctxDraw.lineCap = "round";
        me.ctxDraw.strokeStyle = me.getBrushColor();
        me.ctxDraw.beginPath();
        me.ctxDraw.moveTo(me.lines[i].x, me.lines[i].y);

        me.ctxDraw.lineTo(me.lines[i].x + changeX, me.lines[i].y + changeY);
        me.ctxDraw.stroke();
        me.ctxDraw.closePath();

        return { x: me.lines[i].x + changeX, y: me.lines[i].y + changeY };
    },
    setColor: function (c) {
        this.setBrushColor(c);
    },
    setSize: function (s) {
        this.setBrushSize(s);
    },
    enableDraw: function (b) {
        var scroller = this.getScrollable().getScroller();
        this.setIsDraw(b);
        // disable scrolling during draw
        scroller.stopAnimation();
        scroller.setDisabled(b);
        //
        this.setDrawMode("Pencil");
        //
        if (this.ctxDraw)
            this.ctxDraw.restore();
    },
    enableEraser: function () {
        this.enableDraw(true);
        this.setDrawMode("Eraser");

        //this.ctxDraw.strokeStyle = "rgba(0,0,0,0)";
    },
    clearCanvas: function () {
        this.ctxDraw.clearRect(0, 0, this.drawEl.dom.width, this.drawEl.dom.height);
    },
    getImageBase64: function () {
        //this.canvasSave = document.createElement('canvas');
        //this.ctxSave = this.canvasSave.getContext('2d');
        //$(this.canvasSave).css({ display: 'none', position: 'absolute', left: 0, top: 0 }).attr('width', this.imgEl.dom.width).attr('height', this.imgEl.dom.height);
        ////if a bg image is set, it will automatically save with the image
        //this.ctxSave.drawImage(this.imgEl.dom, 0, 0);
        //this.ctxSave.drawImage(this.drawEl.dom, 0, 0);
        //return this.canvasSave.toDataURL();
        return this.drawEl.dom.toDataURL();
    },
    enableInput: function () {
        this.enableDraw(true);
        this.setDrawMode("Input");
    },
    generateTextInput: function () {
        var me = this;
        var inputItem = Ext.create('Ext.form.Panel', {
            id: 'inputItemPicker',
            modal: true,
            hideOnMaskTap: false,
            centered: true,
            height: 400,
            width: 450,
            style: 'background-color:transparent',
            layout: 'vbox',
            items: [
            {
                docked: 'bottom',
                xtype: 'toolbar',
                items: [
                {
                    text: '取消',
                    handler: function () {
                        inputItem.destroy();
                    }
                },
                {
                    xtype: 'spacer'
                },
                {
                    text: '确定',
                    handler: function () {
                        //获取store
                        var formpanel = Ext.getCmp('txtInputDetail');
                        //setup lines
                        var lines = formpanel.getValue().split('\n');

                        for (var i = 0, ii = lines.length; i < ii; i++) {
                            me.ctxDraw.save();
                            me.ctxDraw.font = "18px Arial";
                            me.ctxDraw.fillStyle = "#996600";
                            //
                            me.ctxDraw.fillText(lines[i], me.currentX, me.currentY + i * 18);
                            me.ctxDraw.restore();
                        }

                        //alert(me.currentX + "  " + me.currentY);
                        inputItem.destroy();
                    }
                }
            ]
            },
            {
                xtype: "fieldset",
                items: [
                {
                    xtype: 'textareafield',
                    id: 'txtInputDetail',
                    height: 300,
                    placeHolder: '请输入内容',
                    required: true,
                    clearIcon: true
                }
                ]
            },
            ]
        });
        Ext.Viewport.add(inputItem);
        inputItem.show();
    },
    /****************/
    startSync: function () {
        var me = this;
        me.setMainSync(true);
        me.getScrollable().getScroller().scrollToTop(true);
    },
    drawPixel: function (xy) {
        sendPixelMessage(xy);
    },
    drawMultiplePixel: function () {
        var me = this;
        me.currentIndex = 0;
        sendPixelMessage(me.pixels[me.currentIndex]);
    },
    stopSync: function () {
        this.setMainSync(false);
    },
    acceptSync: function () {
        this.setSubSync(false);
    },
    acceptMessage: function (data) {
        var me = this;
        me.DrawPoints(data);
        //        if (me.currentIndex < me.pixels.length - 1) {
        //            me.currentIndex++;
        //            sendPixelMessage(me.pixels[me.currentIndex]);
        //        }
        //        else {
        //            me.currentIndex = 0;
        //            me.pixels = new Array();
        //        }
    },
    onScrollerEnd: function (scroller, offsets) {
        var me = this;
        if (me.getMainSync()) {
            sendScrollMessage([scroller.position.x, scroller.position.y]);
        }
        //this.fireEvent('scrollend', scroller, offsets);
    },
    //根据数据重新画线
    DrawPoints: function (jsondata) {
        var obj = jsondata;
        //var user = obj.user;
        //var type = obj.type;
        var data = obj.data;
        this.ctxDraw.beginPath();

        var allxy = obj.split('#'); //data.split('#');
        if (allxy.length > 1) {
            for (i = 1; i < allxy.length; i++) {
                xy = allxy[i];
                if (xy != "") {
                    this.DrawPoint(xy);
                }
            }
        }
    },
    DrawPoint: function (data) {
        // set props
        this.ctxDraw.lineWidth = 4;
        this.ctxDraw.lineCap = "round";
        this.ctxDraw.strokeStyle = "green";
        xy = data.split(",");
        x = xy[0];
        y = xy[1];
        this.ctxDraw.lineTo((x), (y));
        this.ctxDraw.stroke();
    },
    //保留小数点后指定位数的
    formatFloat: function (src, pos) {
        return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
    }
});